import React, { useState } from 'react';
import { Dropdown, Space } from 'antd';
import { MenuItemType } from 'antd/es/menu/interface';
import i18n from 'i18next';
import { BaseCommand, Icon, useCommandManager } from '@amcax/base';
import styles from './styles.module.scss';
import CaretRightOutlined from '@ant-design/icons/lib/icons/CaretRightOutlined';
import { useSolvertStore } from '@/common/store';
import { nmAppDebugLog } from '@/common/utils';

interface IProps {
  cmds: BaseCommand[];
  showLabel?: boolean;
  icon?: string;
  disabled?: boolean;
  label?: string;
  noBg?: boolean;
}
export default function CmdDropDownButton({
  cmds,
  icon,
  disabled,
  label,
  noBg = false,
}: IProps) {
  const { invokeCmd } = useCommandManager();
  const [open, setOpen] = useState(false);
  const [icons, setIcons] = useState(null);
  const { setSolverContent } = useSolvertStore();
  const handleMenuItemClick = (info: any, index: number) => {
    setSolverContent(cmds[index].label);
    nmAppDebugLog('=====cmds==cmds=======', cmds[index]);
    setIcons(cmds[index].icon);
    info.domEvent.stopPropagation();
    const cmd = cmds[index];
    setOpen(false);
    invokeCmd(cmd);
  };
  const menuItems: MenuItemType[] = cmds.map((cmd, index) => {
    return {
      key: cmd.id,
      label: i18n.t(cmd.label),
      icon: (
        <Icon
          name={cmd.icon}
          size={20}
          style={{ fontSize: '24px' }}
        />
      ),
      style: { pointerEvents: 'auto' },
      onClick: (info) => handleMenuItemClick(info, index),
    };
  });

  return (
    <div className={styles['styled-split-button']}>
      <Space.Compact block>
        <Dropdown
          trigger={['click']}
          menu={{
            items: menuItems,
          }}
          placement='bottomLeft'
          onOpenChange={setOpen}
          open={open}>
          <div
            style={{ width: 'max-content', marginBottom: '5px' }}
            className={`${styles._self_drop_btn} ${open ? styles._self_drop_btn_active : ''} ${!noBg && styles._self_drop_btn_bg}`}>
            <Icon
              name={!icons ? icon : icons}
              style={{
                fontSize: '20px',
                opacity: disabled ? 0.3 : 1,
              }}
            />
            <div>{label && i18n.t(label)}</div>
            <CaretRightOutlined
              className={styles._self_drop_btn_icon}
              rotate={45}
            />
          </div>
        </Dropdown>
      </Space.Compact>
    </div>
  );
}
